<?php

namespace app\admin\controller\health\tracking;

use app\common\controller\Backend;
use app\health\model\tracking\HealthTrackingHealth;
use app\health\service\PajkService;

class Health extends Backend
{
    public function index()
    {
        if ($this->request->isAjax()) {
            $service = PajkService::serviceList();
            $params  = $this->request->param();
            $where   = [];
            if (!empty($params['created_at']) && is_array($params['created_at']) && count($params['created_at']) === 2) {
                $where['created_at'] = ['between time', [$params['created_at'][0] . ' 00:00:00', $params['created_at'][1] . ' 23:59:59']];
            }
            $paginate   = HealthTrackingHealth::where($where)
                ->field("count(id) as total_num,type,GROUP_CONCAT(is_use) as is_use")
                ->group('type,user_id')
                ->order('total_num', 'desc')
                ->select();
            $lists      = [];
            $serviceMap = [];
            foreach ($service as $item) {
                $serviceMap[$item['type']] = $item;
            }
            foreach ($paginate as $datum) {
                if (isset($lists[$datum->type])) {
                    $lists[$datum->type]['total_num']  += $datum->total_num;
                    $lists[$datum->type]['is_use']     += array_count_values(explode(',', $datum->is_use))[1] ?? 0;
                    $lists[$datum->type]['total_user'] += 1;
                } else {
                    $lists[$datum->type] = [
                        'service_type' => $datum->type,
                        'service_name' => $serviceMap[$datum->type]['name'] ?? '-',
                        'total_num'    => $datum->total_num,
                        'is_use'       => array_count_values(explode(',', $datum->is_use))[1] ?? 0,
                        'total_user'   => 1,
                    ];
                }
            }
            sort($lists);
            $totalNum = array_column($lists, 'total_num'); // 获取年龄列
            array_multisort($totalNum, SORT_DESC, $lists); // 对年龄列进行升序排序
            $result = ["rows" => $lists];
            $this->success('查看用户', null, $result);
        }
        $this->assign('title', '平安健康服务统计');
        return $this->view->fetch();
    }
}